package vn.edu.saigontech.ncms.service.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.bookstore.Item;
import vn.edu.saigontech.ncms.model.bookstore.OrderDetail;
import vn.edu.saigontech.ncms.service.OrderDetailService;

@SuppressWarnings("unchecked")
public class OrderDetailServiceImpl extends HibernateGenericService<OrderDetail, Long> implements OrderDetailService {

	@Override
	public int sumOfOrder(Item item, Date toDate, boolean includeToDate) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("item", item));

		Criteria orderCriteria = criteria.createCriteria("order");
		if (includeToDate) {
			orderCriteria.add(Restrictions.le("date", toDate));
		} else
			orderCriteria.add(Restrictions.lt("date", toDate));

		criteria.setProjection(Projections.sum("quantity"));
		List<?> list = criteria.list();
		Object value = list.get(0);
		if (value != null) {
			return (Integer) value;
		}
		return 0;
	}

	@Override
	public List<OrderDetail> findByDate(Item item, Date fromDate, Date toDate) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("item", item));
		
		Criteria orderCriteria = criteria.createCriteria("order");
		orderCriteria.add(Restrictions.ge("date", fromDate));
		orderCriteria.add(Restrictions.le("date", toDate));
		
		return criteria.list();
	}
}